<template>
<Card :dis-hover="true">
  <p slot="title">{{title}}</p>
  <Row>
    <Col span="24">
    <Form :model="formItem" :label-width="60" label-position="left">
      <Row :gutter="15">
        <Col span="12">
        <FormItem label="项目名称">
          <Input v-model.trim="formItem.Name"   placeholder="请输入项目名称"></Input>
        </FormItem>
        </Col>
        <Col span="12">
        <FormItem label="起止时间">
          <DatePicker   v-model="dateRange" type="daterange" placement="bottom-end" placeholder="Select date" style="width: 200px"></DatePicker>
        </FormItem>
        </Col>
      </Row>
      <Row :gutter="15">
        <Col span="12">
        <FormItem label="项目级别">
          <Select v-model="formItem.Level"  >
              <Option v-for="item in levelArray" :value="item.value" :key="item.value">{{item.key}}</Option>
            </Select>
        </FormItem>
        </Col>
        <Col span="12">
        <FormItem label="项目来源">
          <Select v-model="formItem.Source"  >
              <Option v-for="item in sourceArray" :value="item.value" :key="item.value">{{item.key}}</Option>
          </Select>
        </FormItem>
        </Col>
      </Row>
      <Row :gutter="15">
        <Col span="12">
        <FormItem label="项目性质">
          <Select v-model="formItem.Character" >
                            <Option v-for="item in chacterArray" :value="item.value" :key="item.value">{{item.key}}</Option>
                    </Select>
        </FormItem>
        </Col>
        <Col span="12">
        <FormItem label="指导老师">
          <Select v-model="formItem.TutorId"  >
                            <Option v-for="item in tutors" :value="item.Id" :key="item.Id">{{item.Abbr}}</Option>
                    </Select>
        </FormItem>
        </Col>
      </Row>
    </Form>
    <div>
      <Form :model="formItem" ref="budgetForm"  label-position="left">
        <Row>
          <Col span="24">
          <FormItem  label="经费预算"  :label-width="60">
            <ButtonGroup shape="circle">
              <!-- <Tooltip content="添加经费预算项" placement="bottom-start" transfer> -->
                <Button type="primary" icon="md-add" ghost @click="budgetOkBtnHandler">
                      添加
                    </Button>
              <!-- </Tooltip> -->
              <!-- <Tooltip content="移除经费预算项" placement="bottom-start" transfer> -->
                <Button type="primary" icon="md-remove" ghost @click="delBudgetHandler">
                    移除
                    </Button>
              <!-- </Tooltip> -->
            </ButtonGroup>
            <span style="margin-left:25px;">总额： {{formItem.Budget}}</span>
               <!-- <Input type="text" v-model="formItem.Budget" width="150" placeholder=""></Input> -->
          </FormItem>
            <div  v-for="(node, index) in formItem.ImsBudget" :key="node.Id" required>
            <Row :gutter="15">
              <Col span="6">
                <FormItem
                :label-width="100"
                  :label="'资金用途 ' + (index+1)"
                :prop="'ImsBudget.' + index + '.Name'"
                :rules="{required: true, message: '资金用途 ' + (index+1) +'是必填项', trigger: 'blur'}"
                  >
                  <Input type="text" v-model.trim="node.Name" placeholder="请输入资金用途..."></Input>
                </FormItem>
              </Col>
              <Col span="6">
                <FormItem
                  :label-width="100"
                  :label="'预算金额(元)'"
                  :prop="'ImsBudget.' + index + '.Budget'"
                  :show-message="false"
                  required
                  >
                  <InputNumber v-model.number="node.Budget" @on-change="budgetChange" :min="0"></InputNumber>
                </FormItem>
              </Col>
              <Col span="10">
                <FormItem
                  label="说明"
                  :label-width="60"
                  :prop="'ImsBudget.' + index + '.Remark'"
                  >
                  <Input type="text" v-model.trim="node.Remark" placeholder="用途说明"></Input>
                </FormItem>
              </Col>
            </Row>
          </div>
          </Col>
        </Row>
      </Form>
    </div>
    </Col>
    <Col span="24" style="padding:6px;">
    <quill-editor v-model="formItem.Content"  :options="editorOption"></quill-editor>
    </Col>

  </Row>
  <div class="footer-btn">
    <ButtonGroup>
      <Button type="primary" icon="ios-paper-plane" :disabled="disableRepeatClick" @click="saveBtnHandler"> 保存 </Button> 
    </ButtonGroup>   
  </div>
</Card>
</template>

<script>
// import { SERVER_CPT_URL } from '@/api/config';
// import KindEditor from '@c/kindEditor';
// import VueHtml5Editor from 'vue-html5-editor';
// import { quillEditor } from 'vue-quill-editor';

import { newApiParams, GUID } from '@/common/utils';
export default {
  name: 'ChangeDetail',
  components: {
    // KindEditor
    // VueHtml5Editor
    // quillEditor
  },
  data () {
    return {
      disableRepeatClick: false, // 防止表单重复提交
      dateRange: [],
      formItem: {
        Level: 0,
        Source: 0,
        Character: 0,
        Budget: 0,
        Start: new Date(),
        End: new Date().setMonth(new Date().getMonth() + 1),
        TutorId: '',
        TutorName: '',
        Content: '',
        Name: '',
        ImsBudget: []
      },
      rules: {},
      tutors: [],
      template: {
        Name: '',
        Level: 0,
        Source: 0,
        Character: 0,
        SubjectId: '',
        SubjectName: '',
        Start: '',
        End: '',
        TutorId: '',
        TutorName: '',
        WordUrl: '',
        Md5: '',
        Content: ''
      },
      levelArray: [
        {
          key: '全国',
          value: 0
        },
        {
          key: '省级',
          value: 1
        },
        {
          key: '市级',
          value: 2
        }
      ],
      sourceArray: [
        {
          key: '科研',
          value: 0
        },
        {
          key: '其它',
          value: 1
        }
      ],
      chacterArray: [
        {
          key: '软件工程',
          value: 0
        },
        {
          key: '其它',
          value: 1
        }
      ],
      editorOption: {
        debug: 'warn',
        modules: {
          toolbar: [
            [{
              'size': ['small', false, 'large']
            }],
            ['bold', 'italic'],
            [{
              'list': 'ordered'
            }, {
              'list': 'bullet'
            }],
            ['link', 'image']
          ],
          history: {
            delay: 1000,
            maxStack: 50,
            userOnly: false
          }
        },
        readOnly: true,
        theme: 'snow',
        placeholder: '前景及可行性分析'
      },
      charge: {
        total: 0,
        item: [],
        flag: false,
        budget: {
          Name: '',
          Remark: '',
          Budget: 1,
          Id: GUID()
        }
      }
    };
  },
  computed: {
    // 是否为新增模式
    addMode () {
      return !!this.$route.params.addMode;
    },
    editable () {
      return this.$route.params.editable;
    },
    title () {
      return this.addMode ? '新建项目' : '项目详情';
    },
    project () {
      return this.$route.params.project ? this.$route.params.project : {};
    }
  },
  watch: {
    // 'formItem.TutorId': function (newVal, oldVal) {
    //   for (let k = 0; k < this.tutors.length; k++) {
    //     if (newVal === this.tutors[k]['Id']) {
    //       console.log(k);

    //       this.formItem.TutorName = this.tutors[k]['Abbr'];
    //       break;
    //     }
    //   }
    // }
    'dateRange': function (newVal, oldVal) {
      if (Array.isArray(newVal) && newVal.length === 2) {
        this.formItem.Start = newVal[0];
        this.formItem.End = newVal[1];
      }
    }
  },
  methods: {
    saveBtnHandler () {
      // console.log('saveBtnHandler');
      
      if (!this.formItem.Name || !this.formItem.Start || !this.formItem.End) {
        console.log('!this.formItem.Name || !this.formItem.Start || !this.formItem.End');
        this.$Message.warning('请检查信息完整性！');
        return;
      }
      this.$refs['budgetForm'].validate((valid) => {
        if (valid) {
          if (this.addMode) {
            this.disableRepeatClick = true;
            // this.formItem.Budgets = this.charge.item;
            this.$api.StartProjectChangeFlow(this.formItem).then((res) => {
              this.$Message.success('保存成功！');
              this.disableRepeatClick = false;
              setTimeout(() => {
                this.$router.push({
                  name: '项目申请'
                });
              }, 500);
            }).catch((err) => {
              if (err) {
                this.$Message.error(err, 4);
                this.disableRepeatClick = false;
              }
            });
          } else {
            this.disableRepeatClick = true;
            this.$api.StartProjectChangeFlow(this.formItem).then((res) => {
              this.$Message.success('保存成功！');
              this.disableRepeatClick = false;
              setTimeout(() => {
                this.$router.push({
                  name: '审核中项目变更'
                });
              }, 500);
            }).catch((err) => {
              if (err) {
                this.$Message.error(err, 4);
                this.disableRepeatClick = false;
              }
            });
          }
        } else {
          this.$Message.warning('请检查信息完整性！');
        }
      });
    },
    selectTutorChange (val) {
      // console.log(val);
      for (let k = 0; k < this.tutors.length; k++) {
        if (val === this.tutors[k]['Id']) {
          this.formItem.TutorName = this.tutors[k]['Abbr'];
          break;
        }
      }
    },
    // 查询导师
    QueryTutor () {
      let params = newApiParams();
      params.query.roleName = '导师';
      this.$api.QueryUsersByRoleNameAndDept(params).then((res) => {
        if (Array.isArray(res.Data) && res.Data.length > 0) {
          this.tutors = res.Data;
          this.formItem.TutorId = this.tutors[0]['Id'];
          this.formItem.TutorName = this.tutors[0]['Abbr'];
        } else {
          console.log(res);
        }
      }).catch((err) => {
        if (err) {
          this.$Message.error(err, 4);
        }
      });
    },
    QueryImsProject (id) {
      let params = newApiParams();
      params.query.Id = id;
      // console.log(params);
      this.$api.QueryImsProjectById(params).then((res) => {
        // console.log(res.Data);
        this.formItem = res.Data;
        this.dateRange = [this.formItem.Start, this.formItem.End];
      }).catch((err) => {
        if (err) {
          this.$Message.error(err, 4);
        }
      });
    },
    addBudgetHandler () {
      this.charge.flag = true;
    },
    budgetOkBtnHandler () {
      let item = {
        Id: GUID(),
        Name: '',
        Remark: '',
        Budget: 1,
        Status: 1,
        Utime: new Date(),
        Ctime: new Date()
      };
      this.formItem.ImsBudget.push(item);
      // this.charge.budget = {
      //   Id: GUID(),
      //   Name: '',
      //   Remark: '',
      //   Budget: 1
      // };
      this.budgetChange();
    },
    delBudgetHandler (node) {
      this.formItem.ImsBudget.pop();
      this.budgetChange();
    },
    budgetChange (val) {
      this.formItem.Budget = 0;
      for (let k = 0; k < this.formItem.ImsBudget.length; k++) {
        this.formItem.Budget += this.formItem.ImsBudget[k].Budget;
      }
    }
  },
  mounted () {
    if (this.addMode) {
      this.QueryTutor();
    } else {
      this.QueryTutor();
      this.formItem = JSON.parse(JSON.stringify(this.project));
      this.dateRange = [this.project.Start, this.project.End];
      this.QueryImsProject(this.project.Id);
      this.dateRange[0] = this.formItem.Start;
      this.dateRange[1] = this.formItem.End;
    }
  }
};
</script>

<style >
.ql-container {
  height: 35rem;
}
.footer-btn {
  text-align: center;
}
</style>
